package com.esd.crm.util;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.log4j.Logger;

/**
 * 文件操作类
 * 
 * @author yufu
 * @email feimeideyanggao@126.com
 * @create 2018年8月12日
 */
public class FileUtils {

	private static Logger logger = Logger.getLogger(FileUtils.class);

	/**
	 * 删除文件或文件夹和其下面的所有文件
	 * 
	 * @param file
	 * @return 返回以供删除了多少个文件
	 */
	public static int deleteFile(File file) {
		int count = 0; // 计数
		if (file.exists()) {
			if (file.isFile()) {
				file.delete();
			} else if (file.isDirectory()) {
				File files[] = file.listFiles();
				for (int i = 0; i < files.length; i++) {
					deleteFile(files[i]);
				}
			}
			file.delete();
			count++;
		} else {
			System.out.println("所删除的文件不存在！");
		}
		return count;
	}

	/**
	 * 将文件转化为字节流
	 * 
	 * @author yufu
	 * @time 2016-4-10 下午1:19:46
	 * @param file
	 * @return
	 */
	public static byte[] getByteFromFile(File file) {
		byte[] buffer = new byte[(int) file.length()];
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(file);
			fis.read(buffer);
		} catch (Exception e) {
			logger.error("文件读取为字节流时发生错误.");
			buffer = null;
		} finally {
			try {
				if (fis != null) {
					fis.close();
				}
			} catch (IOException e) {
				logger.error("关闭字节流时发生错误");
			}
		}
		return buffer;
	}

	/**
	 * 将字节流转换成文件
	 * 
	 * @param buf
	 * @param filePath
	 * @param fileName
	 */
	public static void byte2File(byte[] buf, String filePath, String fileName) {
		BufferedOutputStream bos = null;
		FileOutputStream fos = null;
		File file = null;
		try {
			File dir = new File(filePath);
			if (!dir.exists() && dir.isDirectory()) {
				dir.mkdirs();
			}
			file = new File(filePath + File.separator + fileName);
			fos = new FileOutputStream(file);
			bos = new BufferedOutputStream(fos);
			bos.write(buf);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 保存文件到指定路径
	 * 
	 * @param stream
	 * @param path-
	 *            存放文件的文件夹
	 * @param filename
	 *            - 要保存的文件名
	 * @author ldw
	 * @return
	 */
	public static File saveFileFromInputStream(InputStream stream, String path, String filename) {
		// 检查保存上传文件的文件夹是否存在
		File dirFile = new File(path);
		if (!dirFile.exists()) {
			dirFile.mkdirs();
		}
		if (!path.endsWith(File.separator)) {
			path = path + File.separator;
		}
		File file = null;
		FileOutputStream fs = null;
		try {
			file = new File(path + filename);
			fs = new FileOutputStream(file);
			byte[] buffer = new byte[1024 * 1024];
			int byteread = 0;
			while ((byteread = stream.read(buffer)) != -1) {
				fs.write(buffer, 0, byteread);
				fs.flush();
			}
			fs.close();
			stream.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (fs != null) {
					fs.close();
				}
				if (stream != null) {
					stream.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return file;
	}

	// 根据指定名称查找文件
	public static File getFileByName(String filePath, String fileName) {
		File desFile = null;
		File file = new File(filePath);
		if (file.exists()) {
			File[] files = file.listFiles();
			for (File file2 : files) {
				if (file2.isFile() && file2.getName().contains(fileName)) {
					if (desFile == null) {
						desFile = file2;
					} else {
						long lastModifiedFile2 = file2.lastModified();
						long lastModifiedDesFile = desFile.lastModified();
						if (lastModifiedFile2 > lastModifiedDesFile) {
							desFile = file2;
						}
					}
				}
			}
		}
		return desFile;
	}

	// 删除指定名称文件
	public static void deleteFileByName(String filePath, String fileName) {
		File file = new File(filePath);
		if (file.exists()) {
			File[] files = file.listFiles();
			for (File file2 : files) {
				if (file2.isFile() && file2.getName().contains(fileName)) {
					file2.delete();
				}
			}
		}
	}
}
